import React, { Component } from 'react';
import FieldContext from './Context';

class Field extends Component {

  static contextType = FieldContext

  componentDidMount() {
    this.unregister = this.context.registerFieldEntities(this) // 注册组件实例
  }

  componentWillUnmount() {
    // 注销实例
    if(this.unregister) {
      this.unregister()
    }
  }

  onStoreChange = () => {
    this.forceUpdate()
  }

  getControlled = () => {
    const { getFieldValue, setFieldsValue } = this.context
    const {name} = this.props
    return {
      value: getFieldValue(name), // get
      onChange: (e) => {
        const newValue = e.target.value
        // set
        setFieldsValue({
          [name]: newValue
        })
        // console.log(newValue)
      }
    }
  }

  render() {
    const { children } = this.props
    const returnChild = React.cloneElement(children, this.getControlled())
    return returnChild
  }
}

export default Field